package gb

import (
	"fmt"
	"net/http"

	"gitee.com/tonyjia/gb28181/pkg/gbsip"
	"gitee.com/tonyjia/gb28181/pkg/model/constant"
	"gitee.com/tonyjia/gb28181/pkg/parser"
	"gitee.com/tonyjia/gb28181/pkg/util"
	"github.com/ghettovoice/gosip/sip"
	log "github.com/sirupsen/logrus"
)

/**
 * @Description
 * @Author lulili
 * @Date 2024/10/17 16:43
 */

func RegisterHandler(req sip.Request, tx sip.ServerTransaction) {
	log.Debugf("收到register请求\n%s", req)
	// 判断是否存在 Authorization 字段
	if headers := req.GetHeaders("Authorization"); len(headers) > 0 {
		// 存在 Authorization 头部字段进行鉴权
		//检查expire参数
		h := req.GetHeaders(constant.ExpiresHeader)
		if len(h) != 1 {
			log.Error("not found expires header from request", req)
			return
		}
		expires := h[0].(*sip.Expires)
		// 如果v=0，则代表该请求是注销请求
		if expires.Equals(new(sip.Expires)) {
			log.Debug("expires值为0,该请求是注销请求")
		}
		device, ok := parser.DeviceFromRequest(req)
		if !ok {
			return
		}
		device.Expires = expires.Value()
		err := tx.Respond(sip.NewResponseFromRequest("", req, http.StatusOK, "ok", ""))
		//将设备信息传递回去
		if err != nil {
			log.Error(err)
		}

		err = gbsip.SyncDeviceInfo(device)
		if err != nil {
			log.Errorf("传递设备%v信息失败: %v", device, err)
			return
		}
		//查询设备的信息
		err = gbsip.QueryDevice(device)
		if err != nil {
			log.Errorf("查询设备信息失败，%v", err)
		}
		//查询设备通道信息
		err = gbsip.QueryCatalog(device)
		if err != nil {
			log.Errorf("查询设备通道信息失败，%v", err)
		}
		return
	}

	// 没有存在 Authorization 头部字段
	response := sip.NewResponseFromRequest("", req, http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized), "")
	// 添加 WWW-Authenticate 头
	wwwHeader := &sip.GenericHeader{
		HeaderName: constant.WWWHeader,
		Contents: fmt.Sprintf("Digest nonce=\"%s\", algorithm=%s, realm=\"%s\", qop=\"auth\"",
			"44010200491118000001",
			constant.DefaultAlgorithm,
			util.RandString(32),
		),
	}
	response.AppendHeader(wwwHeader)
	log.Debug("没有Authorization头部信息，生成WWW-Authenticate头部返回：")
	_ = tx.Respond(response)
}
